//
//  StoreViewController.m
//  ScrollView
//
//  Created by Shin Stupid on 12/25/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "StoreViewController.h"
#import "CustomCell.h"
#import "GADBannerView.h"
#import "GADRequest.h"
#import "IPLibTabBarConstants.h"
@interface StoreViewController ()
@property (nonatomic, retain) NSMutableArray *dataSearch;
@end

@implementation StoreViewController
@synthesize dataSearch,adBanner;
static StoreViewController *StoreViewControllerInstance=nil;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
         self.tabBarItem.image = [UIImage imageNamed:@"tabbar_bookshelf.png"];
        StoreViewControllerInstance=self;
        isDelete=FALSE;
        
    }
    return self;
}
+(StoreViewController*)getStoreViewControllerInstance
{
    return StoreViewControllerInstance;
}

-(void)repairData
{
    SAFE_RELEASE( self.dataSearch);
    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];    
    self.dataSearch = [[defaults objectForKey:kData] retain];    
    
//    for (int index=0; index<[dataSearch count]; index++) {
//        NSLog(@"++%@",[dataSearch objectAtIndex:index]);
//        
//    }   
    SAFE_RELEASE(stateArray);
    SAFE_RELEASE(dataDict);
    stateArray=[[NSMutableArray alloc] init];
    dataDict=[[NSMutableDictionary alloc] init];
    /// remake lai array
    
    [self remakeData];    
    [myTableView reloadData];
}
-(void)deleteDataWithString:(NSString*)str
{
    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
    int numberIndex=0;
    for (int i=0; i<[self.dataSearch count]; i++) {
        NSString *iSTR=[self.dataSearch objectAtIndex:i];
        if([iSTR isEqualToString:str])
        {
            numberIndex=i;
            break;
        }
    }

    NSMutableArray *dataSave=[[NSMutableArray alloc] init];
    for (int iJ=0; iJ<[dataSearch count]; iJ++) {
        NSString *iSTR=[self.dataSearch objectAtIndex:iJ];
        if([iSTR isEqualToString:[self.dataSearch objectAtIndex:numberIndex]]==FALSE)
        {        
            [dataSave addObject:[self.dataSearch objectAtIndex:iJ]];
        }
    }
    
    [defaults setObject:dataSave forKey:kData];
    [defaults synchronize];
    SAFE_RELEASE(dataSave);
    
    
    [self repairData];   
}
#pragma mark - View lifecycle
-(void)remakeData
{
    if([self.dataSearch count]<1){return;}
    int index=0;
    do {
        
        NSString *str=[self.dataSearch objectAtIndex:index];        
        int M=[GlobalConfig getFirstDot:str];
        NSString*title=[str substringWithRange:NSMakeRange(M, [str length]-M)];
       
       BOOL isNotHave=FALSE;
        for (int i=0; i<[stateArray count]; i++) {
            
            if([title isEqualToString:[stateArray objectAtIndex:i]])
            {
                isNotHave=TRUE;
            }
        }
        
        if(isNotHave==FALSE)
       {
          //  NSLog(@"Add %@ with title %@",str,title);
           [stateArray addObject:[NSString stringWithFormat:@"%@",title]];
       }
        // add value
        {
            NSMutableArray *getObject =[dataDict objectForKey:[NSString stringWithFormat:@"%@",title]];
            if(getObject!=nil)
            {
                [getObject addObject:str];
                [dataDict setValue:getObject forKey:title];
            }
            else
            {
                NSMutableArray *addObject=[[NSMutableArray alloc] init];
                [addObject addObject:str];
                [dataDict setValue:addObject forKey:title];
                SAFE_RELEASE(addObject);
            }
           
        }
     
        index++;       
    } while (index<[self.dataSearch count]);
    
}
-(void)addBanner
{
    CGPoint origin = CGPointMake(0,0);
    //self.view.frame.size.height - CGSizeFromGADAdSize(kGADAdSizeBanner).height
    // Use predefined GADAdSize constants to define the GADBannerView.
    self.adBanner = [[[GADBannerView alloc] initWithAdSize:kGADAdSizeBanner origin:origin] autorelease];
    // Note: Edit SampleConstants.h to provide a definition for kSampleAdUnitID
    // before compiling.
    self.adBanner.adUnitID = kSampleAdUnitID;
    self.adBanner.delegate = self;
    [self.adBanner setRootViewController:self];
    [self.view addSubview:self.adBanner];
    // self.adBanner.center = CGPointMake(self.view.center.x, self.adBanner.center.y);
    [self.adBanner loadRequest:[self createRequest]];
   // [self.adBanner setBackgroundColor:[UIColor blackColor]];
}
#pragma mark ------------- AN ------
-(void)positionLanguage
{
   //UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation;
    //BOOL isCurrentlyLandscapeView = [GlobalConfig getOrient];//UIDeviceOrientationIsLandscape(deviceOrientation);
    int result=[GlobalConfig getOrient];
    BOOL isCurrentlyLandscapeView=FALSE;
    if(result==-1)
    {
        UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation;
        isCurrentlyLandscapeView=UIDeviceOrientationIsLandscape(deviceOrientation);
    }
    else if(result==0)// landscape
    {
        isCurrentlyLandscapeView=TRUE;
    }
    else if(result==1)// portrait
    {
        isCurrentlyLandscapeView=FALSE;
    }
    if(isCurrentlyLandscapeView==TRUE)
    {
       
        [self setPositionBanner:TRUE];
        [self setPostionlogo:TRUE];
    }
    else
    {       
        [self setPositionBanner:FALSE];
        [self setPostionlogo:FALSE];
        
    }
    
}

-(void)setPositionBanner:(BOOL)isLandScape
{
    if (IS_IPHONE5)
    {
        if(isLandScape==TRUE)
        {
             myTableView.frame=CGRectMake(0, 0, 568, 320);
           self.adBanner.frame=CGRectMake(0,220 , /*self.adBanner.frame.size.width+160*/568, self.adBanner.frame.size.height);
            
        }
        else{
             myTableView.frame=CGRectMake(0, 0, 320, 568);
            self.adBanner.frame=CGRectMake(0,455 , /*self.adBanner.frame.size.width+160*/320, self.adBanner.frame.size.height);
        }
    }
    else
    {
        if(isLandScape==TRUE)
        {
            myTableView.frame=CGRectMake(0, 0, 480, 320);
            self.adBanner.frame=CGRectMake(0,220 , /*self.adBanner.frame.size.width+160*/480, self.adBanner.frame.size.height);
        }
        else{
             myTableView.frame=CGRectMake(0, 0, 320, 480);
            self.adBanner.frame=CGRectMake(0,365 , /*self.adBanner.frame.size.width+160*/320, self.adBanner.frame.size.height);
        }
    }
}
#pragma mark ------------- Add Logo ------
-(void)addLogo
{
    SAFE_RELEASE(logo);
    logo = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"AAP_logo.png"]];
    logo.center=CGPointMake(150, 100);
    logo.alpha=0.3;
    [self.view addSubview:logo];
}
-(void)setPostionlogo:(BOOL)isLandScape
{
    if (IS_IPHONE5)
    {
        if(isLandScape==TRUE)
        {
            logo.center=CGPointMake(280, 100);
        }
        else{
            logo.center=CGPointMake(150, 100);
        }
        
    }
    else
    {
        if(isLandScape==TRUE)
        {
            
            logo.center=CGPointMake(220, 100);
        }
        else{
            logo.center=CGPointMake(150, 100);
        }
    }

}
- (void)viewDidLoad
{
    [super viewDidLoad];    
    [self addLogo];
    myTableView = [[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain];   
    myTableView.delegate = self;
  	myTableView.dataSource = self;
	myTableView.autoresizesSubviews = YES;
    [self.view addSubview:myTableView];
    //myTableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [myTableView setBackgroundColor:[UIColor clearColor]];
    [self addBanner];
    UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation;
    BOOL isCurrentlyLandscapeView = UIDeviceOrientationIsLandscape(deviceOrientation);
   
    
    if (IS_IPHONE5) {
        if(isCurrentlyLandscapeView==TRUE)
        {
            [self setPostionlogo:TRUE];
        }
        else{
            [self setPostionlogo:FALSE];
        }
    }
    else
    {
        
         if(isCurrentlyLandscapeView==TRUE)
         {
             myTableView.frame=CGRectMake(0, 0, 480, 320);
             self.adBanner.frame=CGRectMake(0,220 , /*self.adBanner.frame.size.width+160*/480, self.adBanner.frame.size.height);
             [self setPostionlogo:TRUE];
         }
         else{
             myTableView.frame=CGRectMake(0, 0, 320, 480);
              self.adBanner.frame=CGRectMake(0,365 , /*self.adBanner.frame.size.width+160*/320, self.adBanner.frame.size.height);
             [self setPostionlogo:FALSE];
         }
        
        
    }
    
    UITapGestureRecognizer *tapGesture =[[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(edit_delete)] autorelease];
    tapGesture.numberOfTapsRequired=2;
    [myTableView addGestureRecognizer:tapGesture];
}



-(void)edit_delete
{
    if(isDelete==FALSE)
    {
        [myTableView setEditing:YES animated:YES];
        isDelete=TRUE;
    }
     else
     {
         isDelete=FALSE;
         [myTableView setEditing:NO animated:YES];
     }
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{    
    return YES;
}

#pragma mark -Delegate Table
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [stateArray count];
  
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{    // NSLog(@"& ttt  ");
	return [stateArray objectAtIndex:section];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	NSString* stateKey = [stateArray objectAtIndex:section];
	return [[dataDict objectForKey:stateKey] count];
}

-(NSString*)getData:(int)stt andSection:(int)numberSection
{
    NSMutableArray *strArray=[dataDict objectForKey:[stateArray objectAtIndex:numberSection]];   
   return  [strArray objectAtIndex:stt];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[CustomCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
    }
    // Set up the cell…
    
    int index= indexPath.row;  
    cell.primaryLabel.text = [NSString stringWithFormat:@"http://www.%@",[self getData:index andSection:indexPath.section]];      
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSLog(@"visit link =%@",[self getData:indexPath.row andSection:indexPath.section]);
    NSURL *url =[NSURL URLWithString:[NSString stringWithFormat:@"http://www.%@/",[self getData:indexPath.row andSection:indexPath.section]]]; 
    [[UIApplication sharedApplication] openURL:url];
    
    
    NSLog(@"tableview");
}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)aTableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}
- (void)tableView:(UITableView *)aTableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {

        //NSLog(@"%@",[self getData:indexPath.row andSection:indexPath.section]);
        [self deleteDataWithString:[self getData:indexPath.row andSection:indexPath.section]];
    }
      
}
-(void)dealloc
{
    [super dealloc];
    SAFE_RELEASE(dataSearch);
    SAFE_RELEASE(myTableView);
    SAFE_RELEASE(stateArray);
    SAFE_RELEASE(dataDict);
    SAFE_RELEASE(logo);
}

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{
    [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
   
    if(toInterfaceOrientation == UIInterfaceOrientationPortrait || toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown){
        
        [self changeTheViewToPortrait:YES andDuration:duration];
        [GlobalConfig setOrient:1];
    }
    else if(toInterfaceOrientation == UIInterfaceOrientationLandscapeRight || toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft){
        
        [self changeTheViewToPortrait:NO andDuration:duration];
        [GlobalConfig setOrient:0];
    }
}
- (void) changeTheViewToPortrait:(BOOL)portrait andDuration:(NSTimeInterval)duration{
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:duration];
    
    if(portrait){
        //change the view and subview frames for the portrait view
        
        //[self setpositionLableLandScape:FALSE];
        [self setPositionBanner:FALSE];
        [self setPostionlogo:FALSE];
        
    }
    else{   
        //change the view and subview  frames for the landscape view
     
        //[self setpositionLableLandScape:TRUE];
        [self setPositionBanner:TRUE];
        [self setPostionlogo:TRUE];
        
    }
    
    [UIView commitAnimations];
}
-(void)setpositionLableLandScape:(BOOL)isLandScape
{
    if (IS_IPHONE5) {
        
    }
    else
    {
        
        if(isLandScape==TRUE)
        {
           
        }
        else
        {
            
        }
    }
    
}
#pragma mark GADBannerViewDelegate impl
- (GADRequest *)createRequest
{
    GADRequest *request = [GADRequest request];
    request.testDevices =[NSArray arrayWithObjects:nil];
    return request;
}
// We've received an ad successfully.
- (void)adViewDidReceiveAd:(GADBannerView *)adView {
    NSLog(@"Received ad successfully");
}

- (void)adView:(GADBannerView *)view
didFailToReceiveAdWithError:(GADRequestError *)error {
    NSLog(@"Failed to receive ad with error: %@", [error localizedFailureReason]);
}


@end
